from flask import Flask, render_template, request
from flask_restful import Resource, Api
from vars import shop_config
from pyspark.sql import SQLContext, SparkSession
from pyspark.sql import functions as F
from passwd import dbuser, dbpass, dbhost, dbport

app = Flask(__name__)
api = Api(app)

class Test_shop(Resource):
    def post(self):
        # spark 初始化
        spark = SparkSession. \
            Builder(). \
            appName('sql'). \
            master('local'). \
            getOrCreate()
        # mysql 配置(需要修改)
        prop = {'user': dbuser, 
                'password': dbpass,
                'driver': 'com.mysql.jdbc.Driver'}
        # database 地址(需要修改)
        url = 'jdbc:mysql://' + dbhost + ':' + dbport + '/ratemap'
        # 读取表，data1是用户表，data2是business表
        data1 = spark.read.jdbc(url=url, table='user', properties=prop)
        data2 = spark.read.jdbc(url=url, table='business', properties=prop)

        args = request.json

        print('===get args: {}'.format(args))

        ### 输入的商店名称
        store = args['shopname']
        ### 获取所有数据
        list = data2.collect()
        ### 定义字典，保存商店和对应的评价
        star = {}
        for i in list:
            star[i.name] = i.stars
        return star[store]
        # 关闭spark会话
        spark.stop()

class Shop_sort(Resource):
    def post(self):
        # spark 初始化
        spark = SparkSession. \
            Builder(). \
            appName('sql'). \
            master('local'). \
            getOrCreate()
        # mysql 配置(需要修改)
        prop = {'user': dbuser, 
                'password': dbpass,
                'driver': 'com.mysql.jdbc.Driver'}
        # database 地址(需要修改)
        url = 'jdbc:mysql://' + dbhost + ':' + dbport + '/ratemap'
        # 读取表，data1是用户表，data2是business表
        data1 = spark.read.jdbc(url=url, table='user', properties=prop)
        data2 = spark.read.jdbc(url=url, table='business', properties=prop)

        ### 返回评级排名前100的店铺
        data = []
        count = 100
        info = data2.orderBy(data2.stars.desc()).collect()
        for i in range(0, 100):
            data.append(info[i])
        return data
        # 关闭spark会话
        spark.stop()

api.add_resource(Test_shop, '/')
api.add_resource(Shop_sort, '/sort')

if __name__ == '__main__':
    app.run(debug=True, host=shop_config['host'], port=shop_config['port'])